package com.example.shopsystem.aop1;

import com.example.shopsystem.aop.GetIdUtil;
import com.example.shopsystem.aop.Jurisdiction;
import com.example.shopsystem.dao.AdminMapper;
import com.example.shopsystem.entity.Power;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class AdminPower implements HandlerInterceptor {
    @Autowired
    AdminMapper adminMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler);
        if(handler instanceof HandlerMethod){
            Jurisdiction J=      ((HandlerMethod) handler).getMethodAnnotation(Jurisdiction.class);
            System.out.println(J);
            String str = J.Jurisdiction();

            String id = GetIdUtil.getCurrentUser();
//            System.out.println(id);
            List<Power> list = adminMapper.queryAdminPow(id);
//            System.out.println(list);
            for (Power p:
                    list) {
                if(p.getPowerName().equals(str)){
//                    System.out.println("你可以执行该操作");
                   return true;
                }
            }

//            System.out.println("你不可以执行该操作" );
            response.getWriter().println(    "{" +
                    "\"code\":" + 500 +
                    ", \"message\":\"" + "权限不足" + "\"," +
                    "\"data\":" +" "  + "}");
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
